/**
 * ClassUtil.java
 * Created at 2016-03-01
 * Created by Administrator
 * Copyright (C) 2016 LLSFW, All rights reserved.
 */
package com.llsfw.core.common;

import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AssignableTypeFilter;

/**
 * <p>
 * ClassName: ClassUtil
 * </p>
 * <p>
 * Description: 类工具
 * </p>
 * <p>
 * Author: Administrator
 * </p>
 * <p>
 * Date: 2016年3月23日
 * </p>
 */
public class ClassUtil {

    /**
     * <p>
     * Description: 构造函数
     * </p>
     */
    private ClassUtil() {

    }

    /**
     * <p>
     * Description: 获取在指定包下某个class的所有非抽象子类
     * </p>
     * 
     * @param parentClass 父类
     * @param packagePath 指定包，格式如"com/iteye/strongzhu"
     * @param <E> 泛型类
     * @return 列表
     * @throws ClassNotFoundException 异常
     */
    public static <E> List<Class<E>> getSubClasses(final Class<E> parentClass, final String packagePath)
            throws ClassNotFoundException {
        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
        provider.addIncludeFilter(new AssignableTypeFilter(parentClass));
        Set<BeanDefinition> components = provider.findCandidateComponents(packagePath);
        List<Class<E>> subClasses = new ArrayList<Class<E>>();
        for (BeanDefinition component : components) {
            @SuppressWarnings("unchecked")
            Class<E> cls = (Class<E>) Class.forName(component.getBeanClassName());
            if (Modifier.isAbstract(cls.getModifiers())) {
                continue;
            }
            subClasses.add(cls);
        }
        return subClasses;
    }
}
